<template>
    <div class="goods-add-form">
        <div class="section">
            <h2 class="section-title">修改出库单</h2>
            <el-form ref="ruleFormRef" style="max-width: 1200px;margin: 20px;" :model="othoutord_order" status-icon
                :rules="rules" label-width="auto" class="demo-ruleForm">
                <el-form-item label="出库单号" prop="othoutord_code">
                    <el-input v-model="othoutord_order.othoutord_code" readonly />
                </el-form-item>



                <div style="display: flex; justify-content: space-between;">
                    <div style="width: 48%;">
                        <el-form-item label="出库类型" prop="othoutord_type" style="margin-bottom: 30px;">
                            <el-select v-model="othoutord_order.othoutord_type" placeholder="请选择出库类型"
                                @change="handleSelecttype">
                                <el-option v-for="item in options" :key="item.dict_value" :label="item.dict_label"
                                    :value="item.dict_value" class="option-style" />
                            </el-select>
                        </el-form-item>

                        <el-form-item label="出库仓库" prop="warehouse_code" style="margin-bottom: 30px;">
                            <el-select v-model="othoutord_order.warehouse_code" placeholder="请选择出库仓库"
                                @change="handleSelectChange">
                                <el-option v-for="item in Weahouse" :key="item.warehouse_code"
                                    :label="item.warehouse_name" :value="item.warehouse_code" />
                            </el-select>
                        </el-form-item>
                    </div>

                    <div style="width: 48%;">
                        <el-form-item label="出库库区" prop="zone_code" style="margin-bottom: 30px;">
                            <el-select v-model="othoutord_order.zone_name" placeholder="请选择出库库区" @change="handleSzone">
                                <el-option v-for="item in Warhouse_zone" :key="item.zone_code" :label="item.zone_name"
                                    :value="item.zone_code" />
                            </el-select>
                        </el-form-item>

                      

                    </div>
                </div>
            </el-form>
        </div>

        <!-- 出库产品明细 -->
        <div class="section">
            <h2 class="section-title">出库产品明细</h2>
            <div style="float: left;margin: 10px 0px;">
                <el-button type="primary" @click="productAdd">添加</el-button>
                <el-button @click="productDel">移除</el-button>
            </div>
            <el-table :data="selectedData" border style="width: 100%" :cell-style="{ textAlign: 'center' }"
                :header-cell-style="{
                textAlign: 'center',
                background: '#f5f7fa',
                fontWeight: 'bold',
                position: 'sticky',
                top: 0
            }" ref="selectedTable" @selection-change="handleSelectedChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="stock_name" label="货品名称" fixed="left" width="100" />
                <el-table-column prop="pro_code" label="货品编号" width="150" />
                <el-table-column prop="pro_brand" label="品牌" width="100" />
                <el-table-column prop="stock_model" label="规格型号" width="100" />
                <el-table-column prop="dict_code" label="单位" width="70">
                    <template #default="scope">
                        <span>{{ measureValue(scope.row.dict_code) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="location_code" label="出库库位" width="130">
                    <template #default="scope">
                        <el-select v-model="scope.row.location_name" placeholder="选择库位" size="small"
                            :disabled="isDisabledlocation" @change="(val) => locationEndit(val, scope.row)">
                            <el-option v-for="item in Warehouse_location" :key="item.location_code"
                                :label="item.location_name" :value="item.location_code" />
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column prop="inventory_numder" label="未出库数量" width="100" />
                <el-table-column label="出库数量" width="90">
                    <template #default="scope">
                        <el-input v-model="scope.row.sale_qty" style="width: 75px" :precision="2" :min="0" />
                    </template>
                </el-table-column>
                <el-table-column label="出库单价" width="90">
                    <template #default="scope">
                     
                        <span>{{ scope.row.pro_sale_price }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="出库总金额" width="100">
                    <template #default="scope">
                        <span>{{ scope.row.pro_total_amount }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="pro_cost_price" label="成本金额" width="90" />
                <el-table-column label="成本合计" width="90">
                    <template #default="scope">
                        <span>{{ scope.row.pro_total_cost }}</span>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 合计栏 -->
            <div style="height: 40px; line-height: 40px;">
                <div style="display: inline-block; float: left;">合计</div>
                <div style="display: inline-block; float:right">
                    出库总数量：{{ sale_total_qty }}
                    &nbsp;&nbsp;&nbsp; 出库总金额：{{ Number(sale_total_price).toFixed(2) }}
                    &nbsp;&nbsp;&nbsp;出库产品成本总额：{{ Number(cost_total_proce).toFixed(2) }}
                </div>
            </div>
        </div>

        <!-- 底部按钮 -->
        <div class="button-group">
            <el-button type="primary" @click="handleUpdate">保存修改</el-button>
            <el-button @click="handleClose">关闭</el-button>
        </div>
    </div>

    <!-- 添加产品模态框 -->
    <el-dialog v-model="dialogTableVisible" width="800" title="添加出库产品">
        <hr>
        <div style="margin: 10px 0px;">
            <div style="float: left;margin: 10px 0px;">
                <el-input v-model="productName" style="width: 240px;margin-right: 20px;" placeholder="请输入货品编号/名称" />
                <el-select v-model="dict_code" placeholder="请选择单位" style="width: 240px">
                    <el-option v-for="item in measureOptios" :key="item.dict_value" :label="item.dict_label"
                        :value="item.dict_value" />
                </el-select>
            </div>
            <div style="float: right;margin: 10px 0px;">
                <el-button @click="productReaslt">重置</el-button>
                <el-button type="primary" @click="productEedit">查询</el-button>
            </div>
        </div>

        <el-table ref="multipleTableRef" :data="productData" :cell-style="{ textAlign: 'center' }" :header-cell-style="{
                textAlign: 'center',
                background: '#f5f7fa',
                fontWeight: 'bold',
                position: 'sticky',
                top: 0
            }" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" :selectable="isDisabled" />
            <el-table-column property="pro_code" label="货品编号" width="180" />
            <el-table-column property="stock_name" label="货品名称" width="200" />
            <el-table-column property="stock_model" label="规格型号" />
            <el-table-column property="dict_code" label="单位">
                <template #default="scope">
                    <span>{{ measureValue(scope.row.dict_code) }}</span>
                </template>
            </el-table-column>
            <el-table-column property="pro_cost_price" label="出库单价" />
            <el-table-column property="stock_numder" label="当前库存" />
        </el-table>

        <br>
        <div style="text-align: center;display: flex; justify-content: center;">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 50]"
                :small="false" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="pageCount"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" size="small" />
        </div>
        <hr>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogTableVisible = false">取消</el-button>
                <el-button type="primary" @click="handleConfirmSelection">确定</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, inject, watch } from 'vue'
import dayjs from 'dayjs'
import axios from 'axios'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useWarehouseStore } from '@/storejs/warehouseStore'

// 仓库 store
const warehouseStore = useWarehouseStore()
const othoutord_codego = ref(warehouseStore.othoutord_code || '')

// 表单对象
const othoutordAdd = {
    othoutord_id: 0,
    othoutord_type: '',
    othoutord_code: '',
    

    othoutord_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
    warehouse_code: '',
    warehouse_name: '',
    zone_code: '',
    zone_name: '',
    del_flag: '0',
    update_by: localStorage.getItem('userLName'),
    update_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ')
}
const othoutord_order = reactive({ ...othoutordAdd })


// 表格、分页、弹窗
const ruleFormRef = ref(null)
const rules = reactive({
    othoutord_type: [
        { required: true, message: '请选择出库类型', trigger: 'change' }
    ],
    warehouse_code: [
        { required: true, message: '请选择出库仓库', trigger: 'change' }
    ],
    zone_code: [
        { required: true, message: '请选择出库库区', trigger: 'change' }
    ],
    othoutord_wkeep: [
        { required: true, message: '请选择出库员', trigger: 'change' }
    ],

    /* 明细级联校验（可选：保存时统一校验，不在 rules 中） */
    // 如需行级实时校验，可在 el-table 内使用 :rules
})
const Weahouse = ref([])
const Warhouse_zone = ref([])
const Warehouse_location = ref([])
const options = ref([])
const dialogTableVisible = ref(false)
const productData = ref([])
const currentPage = ref(1)
const pageSize = ref(5)
const pageCount = ref(0)
const productName = ref('')
const dict_code = ref('0')
const measureOptios = ref([])
const multipleTableRef = ref(null)
const selectedProducts = ref([])
const selectedTable = ref(null)
const selectedRows = ref([])
const selectedData = ref([])
const sale_total_qty = ref(0)
const sale_total_price = ref(0)
const cost_total_proce = ref(0)
const isDisabledlocation = ref(false)

const router = useRouter()

/* ---------- 生命周期 ---------- */
onMounted(async() => {
    loadEditData()
    getMeasure()
    getClassify()
    WeahousesSelect()
    productFill()
    productCount()
  
})

/* ---------- watch 计算合计 ---------- */
watch(selectedData, (newVal) => {
    sale_total_qty.value = 0
    sale_total_price.value = 0
    cost_total_proce.value = 0
    newVal.forEach(row => {
        if (isNaN(Number(row.sale_qty))) {
            ElMessage.warning('出库数量必须是数字')
            row.sale_qty = 0
        }
        if (isNaN(Number(row.pro_sale_price))) {
            ElMessage.warning('出库单价必须是数字')
            row.pro_sale_price = 0
        }
        row.pro_total_amount = Number((row.sale_qty || 0) * (row.pro_sale_price || 0)).toFixed(2)
        row.pro_total_cost = Number((row.sale_qty || 0) * (row.pro_cost_price || 0)).toFixed(2)
        sale_total_qty.value += Number(row.sale_qty)
        sale_total_price.value += Number(row.pro_total_amount)
        cost_total_proce.value += Number(row.pro_total_cost)
    })
}, { deep: true })

/* ---------- 加载出库单主表及明细 ---------- */
function loadEditData() {
    axios.get('http://localhost:5181/api/Inv_othoutord/Inv_trf_SelectCode', {
        params: { othoutord_code: othoutord_codego.value },
        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
    }).then(res => {
        const main = res.data[0]
        Object.assign(othoutord_order, {
            othoutord_id: main.othoutord_id,
            othoutord_code: main.othoutord_code,
            othoutord_type: main.othoutord_type,
            othoutord_wkeep: main.othoutord_wkeep,
            othoutord_time: main.othoutord_time,
            othoutord_status: main.othoutord_status,
            warehouse_code: main.warehouse_code,
            warehouse_name: main.warehouse_name,
            zone_code: main.zone_code,
            zone_name: main.zone_name,
          
            create_by: main.create_by,
            create_time: main.create_time,
           
          
        })
        console.log(othoutord_order)

        // 库区
        axios.get('http://localhost:5181/api/Db_warehouse_zone/warehouse_zone', {
            params: { warehouse_code: othoutord_order.warehouse_code },
            headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
        }).then(r => (Warhouse_zone.value = r.data))
        // 库位
        getWarehouse_location(othoutord_order.zone_code)
        // 明细
        loadProductDetails()
    })
}

function loadProductDetails() {
    axios.get('http://localhost:5181/api/Inv_othoutord/Inv_trf_SelectDetail', {
        params: { othoutord_code: othoutord_order.othoutord_code },
        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
    }).then(res => {
        selectedData.value = res.data.map(item => ({
            ...item,
            stock_name: item.pro_name,
            stock_model: item.pro_model,
            dict_code: item.unitmeas_id,
            sale_qty: item.othwrproddt_numder,
            pro_sale_price: item.pro_sale_price || 0,
            pro_cost_price: item.pro_cost_price || 0,
            location_code: item.location_code,
            location_name: item.location_name,
            inventory_numder: item.inventory_numder,
            pro_total_amount: 0,
            pro_total_cost: 0
        }))
    })
}

/* ---------- 保存修改 ---------- */
async function handleUpdate() {
    try {
  

      
        othoutord_order.update_by = localStorage.getItem('userLName')
        othoutord_order.update_time = dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ')
        //明细数据转换
        const detailList = selectedData.value.map(item => ({
            othproddetails_id: item.othproddetails_id || 0,
            othoutord_id: othoutord_order.othoutord_id,
            pro_name: item.stock_name,
            pro_code: item.pro_code,
            pro_brand: item.pro_brand,
            pro_model: item.stock_model,
            unitmeas_id: String(item.dict_code || ''),
            othwrproddt_numder: Number(item.sale_qty),
            inventory_numder: Number(item.inventory_numder || 0),
            location_code: item.location_code ? item.location_code.replace(/\r\n/g, '') : '',
            location_name: item.location_name,
            pro_cost_price: Number(item.pro_cost_price),
            pro_sale_price: Number(item.pro_sale_price)
        }))
        //数据转换
        const payload = {
            inv_OthoutordUpdateDto: {
                othoutord_id: othoutord_order.othoutord_id,
                othoutord_type: othoutord_order.othoutord_type,
                othoutord_code: othoutord_order.othoutord_code,
                othoutord_wkeep: othoutord_order.othoutord_wkeep,
                othoutord_time: othoutord_order.othoutord_time,
                othoutord_status: othoutord_order.othoutord_status,
                warehouse_code: othoutord_order.warehouse_code,
                warehouse_name: othoutord_order.warehouse_name,
                zone_code: othoutord_order.zone_code,
                zone_name: othoutord_order.zone_name,
                update_by: othoutord_order.update_by,
                update_time: othoutord_order.update_time
            },
            inv_Othproddetails: detailList
        }

        console.log("121212",payload);

        const res = await axios.put('http://localhost:5181/api/Inv_othoutord/Inv_othoutord_update', payload, {
            headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
        })
        if (res.data > 0) {
            ElMessage.success('修改成功')
            selectedData.value = []
            handleClose()
        } else {
            ElMessage.error('修改失败')
        }
    } catch (e) {
        console.error(e)
        ElMessage.error('修改过程中发生错误')
    }
}

/* ---------- 仓库、库区、库位联动 ---------- */
function WeahousesSelect() {
    axios.get('http://localhost:5181/api/Db_warehouse/WarehouseBySelect', {
        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
    }).then(res => (Weahouse.value = res.data))
}

const handleSelectChange = (code) => {
    const item = Weahouse.value.find(i => i.warehouse_code === code)
    othoutord_order.warehouse_name = item?.warehouse_name || ''
    axios.get('http://localhost:5181/api/Db_warehouse_zone/warehouse_zone', {
        params: { warehouse_code: code },
        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
    }).then(res => (Warhouse_zone.value = res.data))
}

const handleSelecttype = (val) => {
    const item = options.value.find(i => i.dict_value === val)
    othoutord_order.othoutord_type = item?.dict_value || ''
}

const handleSzone = (code) => {
    const item = Warhouse_zone.value.find(i => i.zone_code === code)
    othoutord_order.zone_name = item?.zone_name || ''
    isDisabledlocation.value = false
    getWarehouse_location(code)
}

function getWarehouse_location(code) {
    axios.get('http://localhost:5181/api/Db_warehouse_location/warehouse_location', {
        params: { zone_code: code },
        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
    }).then(res => (Warehouse_location.value = res.data))
}

const locationEndit = (val, row) => {
    row.location_code = val
    const loc = Warehouse_location.value.find(i => i.location_code === val)
    if (!loc) return ElMessage.error('未找到库位信息')
    row.location_name = loc.location_name
    const total = selectedData.value
        .filter(i => i.location_code === val)
        .reduce((s, i) => s + Number(i.sale_qty || 0), 0)
    if (total > loc.location_available_capacity) {
        ElMessage.error(`库位容量不足！可用：${loc.location_available_capacity}，已分配：${total}`)
        row.location_code = ''
        row.location_name = ''
    }
}

/* ---------- 产品弹窗 ---------- */
function productAdd() { dialogTableVisible.value = true }
const productDel = () => {
    if (!selectedRows.value.length) return ElMessage.warning('请先选择要移除的数据')
    const codes = selectedRows.value.map(i => i.pro_code)
    selectedData.value = selectedData.value.filter(i => !codes.includes(i.pro_code))
    selectedRows.value = []
}

function productFill() {
    axios.get('http://localhost:5181/api/Db_warehouse/GetInv_Stock', {
        params: {
            productName: productName.value,
            dict_code: dict_code.value,
            currentPage: currentPage.value,
            pageSize: pageSize.value
        },
        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
    }).then(res => (productData.value = res.data))
}

function productCount() {
    axios.get('http://localhost:5181/api/Db_warehouse/Inv_StockCount', {
        params: { productName: productName.value, dict_code: dict_code.value },
        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
    }).then(res => (pageCount.value = res.data))
}


function handleSizeChange(val) { pageSize.value = val; productFill(); productCount() }
function handleCurrentChange(val) { currentPage.value = val; productFill(); productCount() }

/* ---------- 字典 ---------- */
function getClassify() {
    axios.get('http://localhost:5181/api/Dict/Get_Dict_Datas', {
        params: { dict_type: 'inv_othoutord' },
        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
    }).then(res => (options.value = res.data))

}



// 查询计量单位
function getMeasure() {
    axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
        params: {
            dict_type: "db_measure"
        }, headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        measureOptios.value = result.data
        measureOptios.value = [{
            dict_value: "0", dict_label: "请选择单位"
        }, ...result.data]
    }).catch((err) => {
        console.info(err)
    });
}
// 根据计量单位id返回计量单位名称
function measureValue(row) {
    if (!row) return "无";
    const parentDept = measureOptios.value.find((sex) => sex.dict_value == row);
    return parentDept ? parentDept.dict_label : "无";
}

/* ---------- 弹窗选择 ---------- */
const handleSelectionChange = (val) => (selectedProducts.value = val)
const handleConfirmSelection = () => {
    selectedData.value = [
        ...selectedData.value,
        ...selectedProducts.value.map(i => ({
            ...i,
            sale_qty: 0,
            inventory_numder: Number(i.othwrproddt_numder || 0), // 未出库数量保留
            pro_total_amount: 0,
            pro_total_cost: 0,
            pro_sale_price: Number(i.pro_sale_price || 0).toFixed(2),
            pro_cost_price: Number(i.pro_cost_price || 0).toFixed(2)
        }))
    ]
    dialogTableVisible.value = false
    multipleTableRef.value?.clearSelection()
}
const handleSelectedChange = (val) => (selectedRows.value = val)
const isDisabled = (row) =>
    !selectedData.value.some(item => item.pro_code === row.pro_code)

const productEedit = () => { productFill(); productCount() }
const productReaslt = () => { productName.value = ''; dict_code.value = '0'; productFill(); productCount() }

/* ---------- 关闭标签 ---------- */
const closeTab = inject('closeTab')
function handleClose() {
    const targetPath = '/main/Inv/Inv_othoutordVue'
    closeTab?.()
    router.push(targetPath)
}
</script>

<style scoped>
.goods-add-form {
    padding: 20px;
    background-color: #fff;
}

.section {
    margin-bottom: 30px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 20px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.section-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 15px;
}

.filter-section {
    margin-bottom: 20px;
    display: flex;
    align-items: center;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
}

.button-group {
    float: right;
    display: flex;
    position: flex;
    text-align: right;
    margin-top: -10px;
    height: 7%;
    align-items: center;
  
    background-color: #ffffff;
    justify-content: flex-end;
    padding-right: 10px
}

.order-input :deep(.el-input__inner) {
    cursor: pointer;
    background-color: #f5f7fa;
}

.order-input:hover :deep(.el-input__inner) {
    border-color: #c0c4cc;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    padding-top: 15px;
    border-top: 1px solid #ebeef5;
}

.el-table--enable-row-hover .el-table__body tr:hover>td {
    background-color: #f5f7fa !important;
    cursor: pointer;
}
</style>
